<template>
  <div
    v-if="External"
    :style="styleExternalIcon"
    class="svg-external-icon svg-icon"
    v-bind="$attrs"
  />
  <svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script setup lang="ts">
import { isExternal } from '@/utils/common'
import { computed } from 'vue'

interface SvgIconProps {
  iconClass: string
  className?: string
  color?: string
}
const props = withDefaults(defineProps<SvgIconProps>(), {
  className: '',
  color: '#333'
})

const External = computed(() => {
  return isExternal(props.iconClass)
})
const symbolId = computed(() => {
  return `#icon-${props.iconClass}`
})
const svgClass = computed(() => {
  if (props.className) {
    return `svg-icon ${props.className}`
  } else {
    return 'svg-icon'
  }
})
const styleExternalIcon = computed(() => {
  return {
    mask: `url(${props.iconClass}) no-repeat 50% 50%`,
    '-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
  }
})
</script>

<style scoped>
.svg-icon {
  width: 16px;
  height: 16px;
  margin: 0 0 0 2px;
  vertical-align: -0.1em;
  fill: currentColor;
  overflow: hidden;
  cursor: pointer;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
